package cm.just;

import java.sql.*;

public class JDBC02 {
    public static Connection getConnection() throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.cj.jdbc.Driver");

        String url = "jdbc:mysql://localhost:3306/javaweb?characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC";
        String user = "root";
        String password = "root";
        return DriverManager.getConnection(url, user, password);
    }

    public static void selectUserByName(Connection connection, String name) throws SQLException {
        String sql = "select * from t_user where username=?";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setString(1,name);
        ResultSet resultSet = preparedStatement.executeQuery();
        try {
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String username = resultSet.getString("username");
                String password = resultSet.getString("password");
                System.out.println("用户编号:" + id + "; 用户名: " + username + "; 密码 " + password);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            connection.close();
            preparedStatement.close();
            resultSet.close();
        }
    }

    public static void main(String[] args) throws SQLException, ClassNotFoundException {
            Connection connection = JDBCUtil.getConnect();
            selectUserByName(connection,"admin");
    }

}
